#include "include/display.h"
#include "include/logger.h"

BITMAP * pages[2] = { NULL, NULL };
int actpg = 0;
int frames = 0;
volatile int frame_lock = 0;

BITMAP * canvas;
volatile int fps;

int SC_WIDTH = 0;
int SC_HEIGHT = 0;
int SC_DEPTH = 0;

/* A local function that helps keep track of the fps */
void reset_fps()
{
	fps = frames;
	frames = 0;
}
END_OF_FUNCTION(reset_fps)

/* A local function to help lock the game to 60 FPS */
void increment_frame_lock()
{
	frame_lock++;
}
END_OF_FUNCTION(increment_frame_lock)


extern int display_on(int w, int h, int d, int f)
{
	set_color_depth(d);
	if (set_gfx_mode(f, w, h, 0, h*2) != 0) {
		if (set_gfx_mode(f, w, h, 0, 0) != 0) {
			if (set_gfx_mode(GFX_SAFE, w, h, 0, 0) != 0) {
	 			set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);
	 			allegro_message("Unable to set any graphic "
	 				"mode\n%s\n", allegro_error);
	 			return 1;
	 		}
      		}
   	}
   	
   	/* create the display pages */
   	pages[0] = create_video_bitmap(w, h);
   	pages[1] = create_video_bitmap(w, h);
   	if(!pages[0] || !pages[1]) {
   		//set_gfx_mode(GFX_SAFE, 0, 0, 0, 0);
   		//allegro_message("Unable to create two video memory pages!\n");
   		LOG_WARN("Page flipping not supported, reverting to buffering!");
   		
   		if((pages[0] = create_bitmap(w, h)) == NULL)
   		{
   			LOG_ERROR("Can not double buffer either. Quitting . . . ");
   			LOG_ERROR("P. S. Buy a new PC ;-)");
   			return 1;
   		};	
   	}
   	canvas = pages[actpg];
   	
   	install_int(reset_fps, 1000);
   	
   	SC_WIDTH = w;
   	SC_HEIGHT = h;
   	SC_DEPTH = d;
   	
   	// Lock the game to 60 fps
   	LOCK_VARIABLE(speed_counter);
        LOCK_FUNCTION(increment_frame_lock);
        install_int_ex(increment_frame_lock, BPS_TO_TIMER(60));
         
   	return 0;
}

extern void sync()
{
	++frames;
	
	if(pages[1]) {
		/* page flipping */
		show_video_bitmap(canvas);
		actpg = 1 - actpg;
		canvas = pages[actpg];
		
	} else {
		/* double buffering */
		blit(canvas, screen, 0, 0, 0, 0, canvas->w, canvas->h);
	}
}

extern void display_off()
{
	if(pages[0]) destroy_bitmap(pages[0]);
	if(pages[1]) destroy_bitmap(pages[1]);
}
